package cn.fl.spl.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.spl.service.ISplCiCfgLogService;
import cn.fl.spl.service.ISplPropInfoService;
import cn.fl.spl.vo.SplCiCfgLogVO;
import cn.fl.spl.vo.SplPropInfoVO;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.SplPropTypCdEnum;
import fl.spl.facade.spl.constant.SplInfoConstant;
import fl.spl.facade.store.condition.SplPropInfoQueryCondition;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 供应商属性表 控制层
 */
@Controller
@RequestMapping("/spl/splpropinfo")
public class SplPropInfoController extends BaseController {

	/**
	 * SplPropInfo 服务层BEAN
	 */
	@Autowired
	private ISplPropInfoService splPropInfoService;

	@Autowired
	private ISplCiCfgLogService splCiCfgLogService;

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SplPropInfoQueryCondition qc = new SplPropInfoQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();
		List<SplPropInfoVO> list = (List<SplPropInfoVO>) pager.getResultList();
		ListPageVO<SplPropInfoVO> listPage = new ListPageVO<SplPropInfoVO>(list, pager.getTotalCount());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		SplPropInfoVO entity = null;
		try {
			entity = new SplPropInfoVO();
			//TODO ADD PARAM
			Long id = this.splPropInfoService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			return result;
		}
		SplPropInfoVO entity = null;
		try {
			entity = new SplPropInfoVO();
			entity.setId(Long.valueOf(id));
			//TODO ADD PARAM
			boolean success = this.splPropInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.splPropInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.newWebLogger("删除数据.[id="+id+"]").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);

		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("移除对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newWebLogger("移除对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			BaseLogUtils.newWebLogger("获取数据,主键不存在.[id="+id+"]").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}
		
		try {
			SplPropInfoVO vo = this.splPropInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.newWebLogger("获取数据,数据不存在.[id="+id+"]").setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);
			}
			result.setData(vo);
			BaseLogUtils.newWebLogger("获取数据.[id="+id+"]").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("根据主键获取对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newWebLogger("根据主键获取对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		
		return result;
	}


	/**
	 * 保存轻卡商家配置
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveSplPropInfo.do", method = { RequestMethod.GET , RequestMethod.POST})
	@ResponseBody
	public Object saveSplPropInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		String methodName = "saveSplPropInfo";
		BaseLogUtils.newWebLogger("根据主键获取对象.请求参数：" + this.getRequestParameter(request)).setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setWarning(false)
				.info();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");

		String splId = request.getParameter("splId");// 供应商ID
		String declaration = request.getParameter("declaration");// 是否开启轻卡商家报单
		String estimate = request.getParameter("estimate");// 是否开启轻卡商家测算

		if (StringUtils.isEmpty(splId)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("供应商ID不能为空");
			BaseLogUtils.newWebLogger("供应商ID为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}
		if (StringUtils.isEmpty(declaration)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("请选择是否开启轻卡商家报单");
			BaseLogUtils.newWebLogger("是否开启轻卡商家报单状态为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}
		if (StringUtils.isEmpty(estimate)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("请选择是否开启轻卡商家测算");
			BaseLogUtils.newWebLogger("是否开启轻卡商家测算状态为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}

		boolean success = true;
		List<SplPropInfoVO> addSplPropInfoVOList = new ArrayList<SplPropInfoVO>(2);
		List<SplPropInfoVO> updateSplPropInfoVOList = new ArrayList<SplPropInfoVO>(2);

		SplPropInfoVO declarationSplPropInfoVO = null;
		SplPropInfoVO estimateSplPropInfoVO = null;

		//记录改变操作 , 修改前
		String declarationB = null;
		String estimateB = null;

		SplPropInfoVO splPropInfoVO = new SplPropInfoVO();
		splPropInfoVO.setIsDel(BaseConstant.IS_YESNO_NO);
		splPropInfoVO.setIsValid(BaseConstant.IS_YESNO_YES);
		splPropInfoVO.setSplId(Long.valueOf(splId));
		splPropInfoVO.setCrtTm(new Date());
		splPropInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());

		SplPropInfoQueryCondition qc = new SplPropInfoQueryCondition();
		qc.setSplId(Long.valueOf(splId));
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		try {
			List<SplPropInfoVO> splPropInfoVOList = this.splPropInfoService.searchList(qc);
			BaseLogUtils.newWebLogger("查询该供应商属性DATA:" + JSONObject.toJSONString(splPropInfoVOList)).setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
			if(CollectionUtils.isNotEmpty(splPropInfoVOList)){
				for (SplPropInfoVO propInfoVO : splPropInfoVOList) {
					if(SplPropTypCdEnum.PROP_LCV_AUTH_CD.getPropTypCd().equals(propInfoVO.getPropTypCd())){
						declarationSplPropInfoVO = new SplPropInfoVO();
						BeanUtils.copyProperties(propInfoVO,declarationSplPropInfoVO);
					}else if(SplPropTypCdEnum.PROP_LCV_ESTIMATE_AUTH_CD.getPropTypCd().equals(propInfoVO.getPropTypCd())){
						estimateSplPropInfoVO = new SplPropInfoVO();
						BeanUtils.copyProperties(propInfoVO,estimateSplPropInfoVO);
					}
				}

			}
			if(null == declarationSplPropInfoVO){
				//之前没有记录 记为否
				declarationB = BaseConstant.IS_YESNO_NO_STR;

				declarationSplPropInfoVO = new SplPropInfoVO();
				BeanUtils.copyProperties(splPropInfoVO,declarationSplPropInfoVO);
				declarationSplPropInfoVO.setPropInfo(declaration);
				declarationSplPropInfoVO.setPropTypCd(SplPropTypCdEnum.PROP_LCV_AUTH_CD.getPropTypCd());
				addSplPropInfoVOList.add(declarationSplPropInfoVO);
			}else{
				if(!declaration.equals(declarationSplPropInfoVO.getPropInfo())){
					declarationB = declarationSplPropInfoVO.getPropInfo();

					declarationSplPropInfoVO.setPropInfo(declaration);
					updateSplPropInfoVOList.add(declarationSplPropInfoVO);
				}
			}
			BaseLogUtils.newWebLogger("轻卡报单DATA:" + JSONObject.toJSONString(declarationSplPropInfoVO)).setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
			if(null == estimateSplPropInfoVO){
				//之前没有记录 记为否
				estimateB = BaseConstant.IS_YESNO_NO_STR;

				estimateSplPropInfoVO = new SplPropInfoVO();
				BeanUtils.copyProperties(splPropInfoVO,estimateSplPropInfoVO);
				estimateSplPropInfoVO.setPropInfo(estimate);
				estimateSplPropInfoVO.setPropTypCd(SplPropTypCdEnum.PROP_LCV_ESTIMATE_AUTH_CD.getPropTypCd());
				addSplPropInfoVOList.add(estimateSplPropInfoVO);
			}else{
				if(!estimate.equals(estimateSplPropInfoVO.getPropInfo())){
					estimateB = estimateSplPropInfoVO.getPropInfo();

					estimateSplPropInfoVO.setPropInfo(estimate);
					updateSplPropInfoVOList.add(estimateSplPropInfoVO);
				}
			}
			BaseLogUtils.newWebLogger("轻卡测算DATA:" + JSONObject.toJSONString(estimateSplPropInfoVO)).setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();

			if(CollectionUtils.isNotEmpty(addSplPropInfoVOList)){
				BaseLogUtils.newWebLogger("新增供应商属性DATA:" + JSONObject.toJSONString(addSplPropInfoVOList)).setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.info();
				DataResultDTO dataResultDTO = this.splPropInfoService.batchAddSplPropInfo(addSplPropInfoVOList);
				if(StringUtils.isEmpty(dataResultDTO.getCode()) || dataResultDTO.getCode().equals(BaseConstant.IS_YESNO_NO_STR)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("操作失败!");
					return result;
				}
			}
			if(CollectionUtils.isNotEmpty(updateSplPropInfoVOList)){
				BaseLogUtils.newWebLogger("修改供应商属性DATA:" + JSONObject.toJSONString(updateSplPropInfoVOList)).setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.info();
				DataResultDTO dataResultDTO = this.splPropInfoService.batchUpdateSplPropInfo(updateSplPropInfoVOList);
				if(StringUtils.isEmpty(dataResultDTO.getCode()) || dataResultDTO.getCode().equals(BaseConstant.IS_YESNO_NO_STR)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("操作失败!");
					return result;
				}
			}

			//添加操作记录
			SplCiCfgLogVO ciCfgLogVO = new SplCiCfgLogVO();
			boolean needAdd = false;
			if (StringUtils.isNotEmpty(declarationB) && !declarationB.equals(declaration)) {
				ciCfgLogVO.setDeclarationB(Integer.parseInt(declarationB));
				ciCfgLogVO.setDeclaration(Integer.parseInt(declaration));
				needAdd = true;
			}
			if (StringUtils.isNotEmpty(estimateB) && !estimateB.equals(estimate)) {
				ciCfgLogVO.setEstimateB(Integer.parseInt(estimateB));
				ciCfgLogVO.setEstimate(Integer.parseInt(estimate));
				needAdd = true;
			}
			if (needAdd) {
				ciCfgLogVO.setDataId(Long.parseLong(splId));
				ciCfgLogVO.setDataTabNm(SplInfoConstant.PRD_SPL_TAB_NAME);
				ciCfgLogVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				ciCfgLogVO.setCrtTm(new Date());
				ciCfgLogVO.setIsDel(BaseConstant.IS_YESNO_NO);
				ciCfgLogVO.setIsNew(BaseConstant.IS_YESNO_YES);

				this.splCiCfgLogService.addAndUpdateOld(ciCfgLogVO);
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("保存轻卡商家配置数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("保存轻卡商家配置数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

}

